<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderSn">
        <el-input v-model="queryParams.orderSn" placeholder="请输入订单编号" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="用户ID" prop="userId" label-width="120px">
        <el-input v-model="queryParams.userId" placeholder="用户ID" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="支付时间">
        <el-date-picker v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd"
          type="datetimerange" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <!-- <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['admin:orderInfo:edit']">导出</el-button> -->
        <!-- <el-button type="primary" icon="el-icon-upload" size="mini" @click="handleImport" v-if="status === 'unSend'"
          v-hasPermi="['admin:orderInfo:edit']">批量导入快递订单</el-button> -->
      </el-form-item>
    </el-form>

    <el-tabs v-model="status" type="card" @tab-click="statusSwitch">
      <el-tab-pane label="全部" name="all" />
      <el-tab-pane label="进行中" name="unSend" />
      <el-tab-pane label="已结束" name="send" />
    </el-tabs>

    <el-table v-loading="loading" :data="orderList" type="expand">
      <el-table-column label="主键" align="center" prop="id" v-if="false" />

      <el-table-column label="订单编号" align="center" prop="orderSn" />
      <el-table-column label="下单用户" align="center" prop="userId" />
      <el-table-column label="购买金额" align="center" prop="creativeAmt" />
      <el-table-column label="获得收益金额" align="center" prop="usdtAmt">
      </el-table-column>
      <el-table-column label="GPU金额" align="center" prop="gpuAmt" />
      <el-table-column label="订单天数" align="center" prop="validDays" />
      <el-table-column label="订单天数" align="center" prop="validDays" />
      <el-table-column label="订单收益率" align="center" prop="creativePerStr" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="过期时间" align="center" prop="overTime" />

      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.orderStatus === -1">已失效</span>
          <span v-if="scope.row.orderStatus === 0">进行中</span>
          <span v-if="scope.row.orderStatus === 1">已结束</span>
          <span v-if="scope.row.orderStatus === 2">已发货</span>
          <span v-if="scope.row.orderStatus === 3">已完成</span>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 改地址对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="addrRules" label-width="120px">
        <el-form-item label="订单号" prop="orderId" v-show="false">
          <el-input v-model="form.orderId" />
        </el-form-item>
        <el-form-item label="收件人姓名" prop="addrName">
          <el-input v-model="form.addrName" placeholder="请输入收件人名字" />
        </el-form-item>
        <el-form-item label="收件人手机号" prop="addrTel">
          <el-input v-model="form.addrTel" placeholder="请输入手机号" />
        </el-form-item>
        <!--        "-->
        <el-form-item label="省市区" required>
          <el-form-item label="" prop="category1Id">
            <el-select placeholder="请选择" v-model="form.category1Id" @change="handler1">
              <el-option :label="c1.areaName" :value="c1.id" v-for="c1 in list1" :key="c1.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="category2Id">
            <el-select placeholder="请选择" v-model="form.category2Id" @change="handler2">
              <el-option :label="c2.areaName" :value="c2.id" v-for="c2 in list2" :key="c2.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="category3Id">
            <el-select placeholder="请选择" v-model="form.category3Id" @change="handler3">
              <el-option :label="c3.areaName" :value="c3.id" v-for="c3 in list3" :key="c3.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form-item>
        <el-form-item label="详细地址" prop="addrInfo">
          <el-input v-model="form.addrInfo" placeholder="请输入详细地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 订单详情-->
    <el-dialog title="订单详情" :visible.sync="openOrderDetail" width="1000px" append-to-body @close="cancel">
      <el-form ref="form" :inline="true" :model="form" label-width="120px">
        <el-col :span="24" style="padding: 20px 0; font-weight: bolder">
          <span>用户信息:</span>
          <!-- <el-form-item label="商品信息:"></el-form-item> -->
        </el-col>
        <el-row>
          <el-col :span="24" style="
              border: 1px solid #000;
              background-color: rgba(226, 226, 226, 0.28);
              border-radius: 10px;
            ">
            <el-form-item :span="3" label="用户ID">{{
              form.userId
            }}</el-form-item>
            <el-form-item :span="3" label="用户账号">{{
              form.account
            }}</el-form-item>
            <el-form-item :span="3" label="收货人">{{
              form.addrName
            }}</el-form-item>
            <el-form-item :span="3" label="收货手机号">{{
              form.addrTel
            }}</el-form-item>
            <el-form-item :span="20" label="省市区">{{
              form.addrArea
            }}</el-form-item>
            <el-form-item :span="20" label="地址详情">{{
              form.addrInfo
            }}</el-form-item>
          </el-col>
        </el-row>
        <el-col :span="24" style="padding: 20px 0; font-weight: bolder">
          <span>商品信息:</span>
          <!-- <el-form-item label="商品信息:"></el-form-item> -->
        </el-col>
        <el-row>
          <el-col :span="24" style="
              border: 1px solid #000;
              background-color: rgba(226, 226, 226, 0.28);
              border-radius: 10px;
              padding-top: 20px;
            ">
            <el-col :span="24">
              <el-form-item label="商品图">
                <el-image :src="requestUrl + form.mainImg" style="
                    width: 140px;
                    height: 140px;
                    float: left;
                    display: inline-block;
                  " :preview-src-list="[requestUrl + form.mainImg]" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <!-- {{ form.goodName }} -->
              <el-form-item label="商品名称">
                <span style="width: 700px; display: block">{{
                  form.goodsName
                }}</span>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="商品单价" style="color: red">￥{{ form.goodsPrice }}</el-form-item>
              <el-form-item label="购买数量">{{ form.goodsNum }}</el-form-item>
              <el-form-item :span="12" label="订单总额" style="color: red">￥{{ form.money }}</el-form-item>
              <el-form-item :span="12" label="订单实收" style="color: red">￥{{ form.paidIn }}</el-form-item>
              <el-form-item :span="23" label="赠送绿色积分" style="color: red">{{
                form.totalLgwAmt
              }}</el-form-item>
              <el-form-item :span="23" label="赠送消费券" style="color: red">{{
                form.totalConsumeAmt
              }}</el-form-item>
            </el-col>
            <el-col>
              <el-form-item :span="23" label="订单编号">{{
                form.orderNo
              }}</el-form-item>
            </el-col>
            <el-col>
              <el-form-item :span="12" label="下单时间">{{
                form.orderTime
              }}</el-form-item>
              <el-form-item :span="12" label="付款时间">{{
                form.payTime
              }}</el-form-item>
              <el-form-item :span="12" label="发货时间">{{
                form.sendTime
              }}</el-form-item>
              <el-form-item :span="12" label="收货时间">{{
                form.receiveTime
              }}</el-form-item>
            </el-col>
            <el-col>
              <el-form-item :span="4" label="支付方式:" v-if="form.payType == 1">支付宝支付</el-form-item>
              <el-form-item :span="4" label="支付方式:" v-if="form.payType == 2">微信支付</el-form-item>
              <el-form-item :span="4" label="支付方式:" v-if="form.payType == 3">余额支付</el-form-item>
            </el-col>

          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel"> 关 闭</el-button>
      </div>
    </el-dialog>
    <!-- 提醒发货 -->
    <el-dialog :title="title" :visible.sync="open1" width="700px" append-to-body>
      <el-form ref="sendForm" :model="sendForm" label-width="120px" size="mini" :rules="courierRules">
        <el-form-item label="快递单号" prop="courierId">
          <el-input v-model="sendForm.courierId" />
        </el-form-item>
        <el-form-item label="快递公司" prop="courierCompany">
          <el-input v-model="sendForm.courierCompany" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deliver">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <div class="down_wrapper" style="margin-bottom: 20px">
        <div class="el-upload__tip">
          <el-link type="info" style="font-size: 25px; color: #00afff" @click="importTemplate">1. 下载模板
          </el-link>
        </div>
        <div>
          <div class="el-upload__tip" style="color: red; font-size: 20px">
            2.下载模板录入文件之后将其上传
          </div>
        </div>
      </div>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  creativeorderlist,
  getOrder,
  complete,
  updateOrder,
  getAreaList,
  send,
  exportOrder,
  importTemplate,
} from "@/api/admin/order";
import { getToken } from "@/utils/auth";

export default {
  name: "Order",
  data() {
    return {
      requestUrl: this.$img.requestUrl,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 日期范围
      dateRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false, //地址弹窗
      openAddr: false, //地址
      openCourier: false, //快递
      openOrderDetail: false, //订单详情
      openConplete: false, //收货弹窗
      // 查询参数
      status: "all",
      startMounth: "",
      endMounth: "",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderStatus: null,
        orderNo: null,
        addrName: null,
        addrTel: null,
        userId: null,
        account: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      sendRules: {},
      courierRules: {
        courierCompany: [
          { required: true, message: "物流公司不能为空", trigger: "blur" },
        ],
        courierId: [
          { required: true, message: "物流单号不能为空", trigger: "blur" },
        ],
      },
      addrRules: {
        addrName: [
          { required: true, message: "收件人名字不能为空", trigger: "blur" },
        ],
        addrTel: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error("请输入正确的手机号"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        category1Id: [
          { required: true, message: "请选择一级地址", trigger: "blur" },
        ],
        category2Id: [
          { required: true, message: "请选择二级地址", trigger: "blur" },
        ],
        category3Id: [
          { required: true, message: "请选择三级地址", trigger: "blur" },
        ],
        addrInfo: [
          { required: true, message: "详细地址不能为空", trigger: "blur" },
        ],
      },
      list1: [], //一级分类数据
      list2: [], //二级分类数据
      list3: [], //三级分类数据
      cForm: {
        //收集相应的一级二级分类的id
        category1Id: "",
        category2Id: "",
        category3Id: "",
      },
      sendForm: {},
      open1: false,
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/admin/order/importData",
      },
    };
  },
  created() {
    this.getList();
    // this.getCategory1List();
  },

  methods: {
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      creativeorderlist(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.orderList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      (this.open = false), //地址弹窗
        (this.openAddr = false), //地址
        (this.openCourier = false), //快递
        (this.openOrderDetail = false), //订单详情
        (this.openConplete = false);
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    statusSwitch(tab) {
      const status = tab.name;
      let projectStatus = "";
      if (status === "all") {
        projectStatus = "";
      } else if (status === "unSend") {
        projectStatus = 0;
      } else if (status === "send") {
        projectStatus = 1;
      } else if (status === "complete") {
        projectStatus = 3;
      }
      this.queryParams.orderStatus = projectStatus;
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    complete(row) {
      const self = this;
      this.$confirm("是否确认客户已经收到货?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          complete(row.orderNo).then((response) => {
            self.msgSuccess("收货成功");
            self.getList();
          });
        })
        .catch(function () { });
    },
    /** 地址提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.orderId != null) {
            updateOrder(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.openCourier = false;
                this.getList();
              }
            });
          }
        } else {
        }
      });
    },
    /** 修改地址按钮操作,回显地址数据*/
    handleUpdate(row) {
      this.reset();
      const id = row.orderNo;
      getOrder(id).then((response) => {
        this.form = response.data;
        this.form.category1Id = "";
        this.form.category2Id = "";
        this.form.category3Id = "";
        let addr = this.form.addrArea;
        this.cForm.category1Id = "";
        this.cForm.category2Id = "";
        this.cForm.category3Id = "";

        //回显三级地址
        var obj1 = {};
        var obj2 = {};
        var obj3 = {};
        let arr = addr.split(/\s+/);
        if (arr.length == 3) {
          let addr1 = arr[0];
          let addr2 = arr[1];
          let addr3 = arr[2];

          obj1 = this.list1.find(function (i) {
            return i.areaName === addr1;
          });
          if (typeof obj1 != "undefined") {
            this.form.category1Id = obj1.id;
            this.cForm.category1Id = obj1.id;
            getAreaList(obj1.id).then((response) => {
              this.list2 = response.data;
              obj2 = this.list2.find(function (i) {
                return i.areaName === addr2;
              });
              this.form.category2Id = obj2.id;
              this.cForm.category2Id = obj2.id;
              getAreaList(obj2.id).then((response) => {
                this.list3 = response.data;
                obj3 = this.list3.find(function (i) {
                  return i.areaName === addr3;
                });
                this.form.category3Id = obj3.id;
                this.cForm.category3Id = obj3.id;
                this.open = true;
                this.title = "修改收货地址";
              });
            });
          }
        }
      });
    },
    getCategory1List() {
      getAreaList(0).then((response) => {
        console.log(response, "地区");
        this.list1 = response.data;
      });
    },

    async handler1() {
      // 一级分类的select事件的回调（当一级分类的option发生变化时拿到对应二级分类的数据
      //清除数据
      this.list2 = [];
      this.list3 = [];
      this.cForm.category1Id = this.form.category1Id;
      this.cForm.category2Id = "";
      this.cForm.category3Id = "";
      let parentId = this.cForm.category1Id;
      getAreaList(parentId).then((response) => {
        this.list2 = response.data;
      });
    },
    async handler2() {
      // 二级分类的事件回调（当二级分类的option发生变化时拿到对应三级分类的数据
      //   清除三级分类的数据
      this.list3 = [];
      this.cForm.category2Id = this.form.category2Id;
      this.cForm.category3Id = "";
      getAreaList(this.cForm.category2Id).then((response) => {
        this.list3 = response.data;
      });
    },
    async handler3() {
      let parentId1 = this.cForm.category1Id;
      let parentId2 = this.cForm.category2Id;
      this.cForm.category3Id = this.form.category3Id;
      let parentId3 = this.cForm.category3Id;
      var obj1 = {};
      var obj2 = {};
      var obj3 = {};
      obj1 = this.list1.find(function (i) {
        return i.id === parentId1;
      });
      obj2 = this.list2.find(function (i) {
        return i.id === parentId2;
      });
      obj3 = this.list3.find(function (i) {
        return i.id === parentId3;
      });
      this.form.addrArea =
        obj1.areaName + " " + obj2.areaName + " " + obj3.areaName;
    },
    send(row) {
      this.reset1();
      this.title = "填写快递信息";
      this.open1 = true;
      this.sendForm.orderId = row.orderId;
    },
    reset1() {
      this.resetForm("sendForm");
    },
    cancel1() {
      this.reset1();
      this.open1 = false;
    },
    /** 地址提交按钮 */
    deliver() {
      this.$refs["sendForm"].validate((valid) => {
        if (valid) {
          if (this.sendForm.orderId != null) {
            send(this.sendForm).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("发货成功");
                this.open1 = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    handleDetail(row) {
      this.resetForm("form");
      const id = row.orderNo;
      getOrder(id).then((response) => {
        this.form = response.data;
        this.openOrderDetail = true;
        this.title = "查看订单详情";
      });
    },
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出订单数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportOrder(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () { });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "快递订单导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
